//package com.bz.controller;
//
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
//
//import java.io.IOException;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.CopyOnWriteArrayList;
//
//@RestController
//public class ChatController {
//
//    private final Map<String, CopyOnWriteArrayList<SseEmitter>> channelEmitters = new ConcurrentHashMap<>();
//
//    /**
//     * 处理 SSE 连接请求并根据频道参数添加到相应的列表中
//     * channel 为用户id
//     */
//    @GetMapping(value = "/stream/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public SseEmitter handleSse(@PathVariable String userId) {
//        if (!channelEmitters.containsKey(userId)) {
//            channelEmitters.put(userId, new CopyOnWriteArrayList<>());
//        }
//        SseEmitter emitter = new SseEmitter();
//        channelEmitters.get(userId).add(emitter);
//
//        // 当连接断开时移除emitter
//        emitter.onCompletion(() -> channelEmitters.get(userId).remove(emitter));
//        emitter.onTimeout(() -> channelEmitters.get(userId).remove(emitter));
//
//        // 设置超时时间
//        try {
//            emitter.send(SseEmitter.event().comment("Connected to userId: " + userId));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        emitter.completeWithError(new RuntimeException("Connection timeout"));
//
//        return emitter;
//    }
//
//    // 广播消息给指定频道的所有连接客户端
//    @PostMapping("/broadcast/{channel}")
//    public void broadcastMessage(@PathVariable String channel, @RequestBody String message) {
//        if (channelEmitters.containsKey(channel)) {
//            channelEmitters.get(channel).forEach(emitter -> {
//                try {
//                    emitter.send(SseEmitter.event().data(message));
//                } catch (Exception e) {
//                    channelEmitters.get(channel).remove(emitter);
//                }
//            });
//        }
//    }
//
//    // 可选：列出所有可用频道
//    @GetMapping("/channels")
//    public Iterable<String> listChannels() {
//        return channelEmitters.keySet();
//    }
//}